import { NextApiRequest, NextApiResponse } from 'next';
import { format } from 'date-fns'; // 日期转化
import md5 from 'md5';
import { withIronSessionApiRoute } from 'iron-session/next';// sessionp库
import { ISession } from 'pages/api/index';
import request from 'service/fetch';
import { encode } from 'js-base64';
import { ironOptions } from 'config/index'; // sessionp配置
// 使用sessionp
export default withIronSessionApiRoute(sendVerifyCode, ironOptions);
// 短信校验接口
async function sendVerifyCode(req: NextApiRequest, res: NextApiResponse) {
    // const session: any = req.session as any;
    const { to = '', templateId = '1' } = req.body;
    // 短信平台key
    const AppId = '8aaf07087d7fb5f6017d950ce83f04e1';
    const AccountId = '8aaf07087d7fb5f6017d950ce72c04da';
    const AuthToken = '91725ff244364cda9f1e1ea7d471e124';
    const NowDate = format(new Date(), 'yyyyMMddHHmmss'); //日期转化
    const SigParameter = md5(`${AccountId}${AuthToken}${NowDate}`);
    const Authorization = encode(`${AccountId}:${NowDate}`);
    const verifyCode = Math.floor(Math.random() * (9999 - 1000)) + 1000;
    const expireMinute = '5';
    const url = `https://app.cloopen.com:8883/2013-12-26/Accounts/${AccountId}/SMS/TemplateSMS?sig=${SigParameter}`;
    console.log(url,'url')
    // 调用第三方登录平台 获取短信
    const response = await request.post(
        url,
        {
          to,
          templateId,
          appId: AppId,
          datas: [verifyCode, expireMinute],
        },
        {
          headers: {
            Authorization,
          },
        }
      );
    
      console.log(verifyCode)
      console.log(response);
      const { statusCode, templateSMS, statusMsg } = response as any;
    
      if (statusCode === '000000') {
        // session.verifyCode = verifyCode;
        // await session.save();
        // res.status(200).json({
        //   code: 0,
        //   msg: statusMsg,
        //   data: {
        //     templateSMS
        //   }
        // });
      } else {
        res.status(200).json({
          code: statusCode,
          msg: statusMsg
        });
      }
}